package com.thread.exector;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;

public class ExecutorResultManager {

	static class CallResult {
		private String name;
		private Long time;

		public CallResult(String name, Long time) {
			this.name = name;
			this.time = time;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public Long getTime() {
			return time;
		}

		public void setTime(Long time) {
			this.time = time;
		}
	}

	public static void main(String[] args) {
		// 队列
		final BlockingQueue<Future<CallResult>> futures = new LinkedBlockingQueue<Future<CallResult>>();

		// 生产者
		new Thread() {
			@Override
			public void run() {
				ExecutorService pool = Executors.newCachedThreadPool();

				for (int i = 0; i < 10; i++) {
					final int index = i;
					Future<CallResult> submit = pool.submit(new Callable<CallResult>() {

						@Override
						public CallResult call() throws Exception {
							Long start = (new Date()).getTime();
							int sleep = (new Random()).nextInt(1000);
							Thread.sleep(sleep);
							System.out.println(sleep);
							return new CallResult("task done "+index,start);
						}

					});
					try {
						futures.put(submit);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		// 消费者
		new Thread() {
			@Override
			public void run() {
				int all = futures.size();
				while(all>0){
					for (Future<CallResult> future : futures) {
						if (future.isDone()) {
							all--;
							try {
								// 处理业务
								// .............
								Long now = (new Date()).getTime();
								System.out.println(future.get().getName()+"耗时："+(now - future.get().getTime()));
							} catch (InterruptedException e) {
								e.printStackTrace();
							} catch (ExecutionException e) {
								e.printStackTrace();
							}
						}
						;
					}
				
				}
			}
		}.start();
		
	}

}